package com.wcity.manage.service.impl;

import com.wcity.manage.common.context.Constants;
import com.wcity.manage.common.utils.DigestUitl;
import com.wcity.manage.common.utils.JSONUtil;
import com.wcity.manage.common.utils.Log;
import com.wcity.manage.common.utils.StringUtil;
import com.wcity.manage.dao.mapper.BindVerifyMapper;
import com.wcity.manage.dao.mapper.RegisterMapper;
import com.wcity.manage.dao.mapper.TokenHistoryMapper;
import com.wcity.manage.dao.model.Register;
import com.wcity.manage.dao.model.TokenHistory;
import com.wcity.manage.service.CommentService;
import com.wcity.manage.service.RegisterService;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by jn on 2016/12/10.
 * 注册用户service
 */
@Service
public class RegisterServiceImpl implements RegisterService {

    @Override
    public String register(String phone, String code, String pwd, String cpwd) {

        String errorMsg = commentService.checkCode( phone, code, 1 );
        if ( !StringUtil.isBlank( errorMsg ) ) return errorMsg;

        if ( registerMapper.findByPhone( phone ) != null ) return "用户已存在";

        Register register = new Register();
        register.setPhone( phone );
        register.setPassword( DigestUitl.pwd( pwd ) );
        // 默认昵称
        register.setNickname( "昵称" );
        register.setIcon( Constants.REGISTER_DEFAULT_ICON );

        try {
            if ( registerMapper.insert( register ) <= 0 ) return "注册失败";
        } catch (DataAccessException e) {
            Log.error( "用户注册失败" );
            return "注册失败，服务器异常";
        }

        return "";
    }

    @Override
    public String resetPwd(String phone, String code, String pwd) {

        String errorMsg = commentService.checkCode( phone, code, 2 );

        if ( !StringUtil.isBlank( errorMsg ) ) return errorMsg;

        Register register = registerMapper.findByPhone( phone );
        if ( register == null ) return "重置失败，用户不存在";

        try {
            if ( registerMapper.resetPwd( DigestUitl.pwd( pwd ), register.getId() ) <= 0 ) return "重置失败";

            // 清除token
            registerMapper.deleteByRegisterId( register.getId() );
        } catch (Exception e) {
            Log.error("重置密码异常");
            return "重置失败，服务器异常";
        }

        return "";
    }

    @Override
    public Object login(String phone, String pwd) {

        Register register = registerMapper.findByPhone( phone );

        if ( register == null || !register.getPassword().equals( DigestUitl.pwd( pwd ) ) )
            return "用户不存在或密码错误";

        // 不能多处登陆，直接更新token
        String token = StringUtil.getUUID();

        try {

            if ( registerMapper.authToken( token, register.getId() ) <= 0 ) return "服务器异常";

            // 登陆过则更新token记录
            if ( !StringUtil.isBlank( register.getToken() ) ) {
                TokenHistory history = new TokenHistory();
                history.setRegisterId( register.getId() );
                history.setToken( register.getToken() );
                history.setCreateTime( register.getExpireTime() );
                historyMapper.insert( history );
            }

        } catch (DataAccessException e) {
            Log.error("token更新异常");
            return "服务器异常";
        }

        // 更新登陆时间
        Register query = new Register();
        query.setId( register.getId() );
        registerMapper.update( query );

        Map<String,Object> map = new HashMap<>();
        map.put("registerId",register.getId());
        map.put("token",token);

        return map;
    }

    @Override
    public String logout(String registerId) {

        // 清除token
        registerMapper.deleteByRegisterId( Integer.parseInt( registerId ) );

        return "";
    }

    @Override
    public String updatePwd(String registerId, String pwd, String cpwd) {

        Register register = registerMapper.find( Integer.parseInt( registerId ) );

        if ( register == null || !register.getPassword().equals( DigestUitl.pwd( pwd ) ) )
            return "用户不存在或密码错误";

        registerMapper.resetPwd( DigestUitl.pwd( cpwd ), Integer.parseInt( registerId ) );

        // 清除token
        registerMapper.deleteByRegisterId( register.getId() );

        return "";
    }

    @Override
    public String updateInfo(String registerId, String nickname, String icon) {

        Register register = registerMapper.find( Integer.parseInt( registerId ) );
        if ( register == null ) return "用户不存在";

        Register query = new Register();
        query.setId( register.getId() );

        if ( !StringUtil.isBlank( nickname ) ) query.setNickname( nickname );
        if ( !StringUtil.isBlank( icon ) ) query.setIcon( icon );

        registerMapper.update( query );

        return "";
    }

    @Override
    public Object bindVerify(String registerId, String code) {

        Register register = registerMapper.find( Integer.parseInt( registerId ) );

        // type = 3  更改绑定手机号验证码
        String errorMsg = commentService.checkCode( register.getPhone(), code, 3 );

        if ( !StringUtil.isBlank( errorMsg ) ) return errorMsg;

        // 清除uuid
        bindVerifyMapper.deleteByRegisterId( Integer.parseInt( registerId ) );

        String uuid = StringUtil.getUUID();
        bindVerifyMapper.insert( uuid, Integer.parseInt( registerId ) );

        Map<String,Object> map = JSONUtil.getSuccessJson();
        map.put("verifyCode",uuid);

        return map;
    }

    @Override
    public String updateBindPhone(String registerId,String verifyCode, String newPhone, String code) {

        String errorMsg = commentService.checkCode( newPhone, code, 3 );

        if ( !StringUtil.isBlank( errorMsg ) ) return errorMsg;

        Date expireTime = bindVerifyMapper.getExpireTime( verifyCode, Integer.parseInt( registerId ) );

        if ( expireTime == null ) return "验证失败";

        long cur = System.currentTimeMillis();
        if ( ( cur - expireTime.getTime() ) > Constants.CHANGE_PHONE_TIME ) {
            bindVerifyMapper.deleteByRegisterId( Integer.parseInt( registerId ) );
            return "操作超时";
        }
        // 清除验证code
        bindVerifyMapper.deleteByRegisterId( Integer.parseInt( registerId ) );

        Register r = registerMapper.find( Integer.parseInt( registerId ) );
        if ( r.getPhone().equals( newPhone ) ) return "新手机号与旧手机号相同";

        Register register = new Register();
        register.setPhone( newPhone );
        register.setId( Integer.parseInt( registerId ) );
        // 更新手机号
        registerMapper.update( register );

        // 清空token
        registerMapper.deleteByRegisterId( Integer.parseInt( registerId ) );

        return "";
    }

    @Override
    public Object registerInfo(String registerId) {

        Register register = registerMapper.find( Integer.parseInt( registerId ) );

        if ( register == null ) return "用户不存在";

        Map<String,Object> map = new HashMap<>();
        // 头像
        map.put("icon",register.getIcon());
        // 昵称
        map.put("nickname",register.getNickname());
        // 手机号
        map.put("phone",register.getPhone());
        // 小区名
        map.put("blockName",register.getBlock().getBlockName());
        // 小区id
        map.put("blockId",register.getBlock().getId());
        // 楼栋
        map.put("building",register.getBuilding());
        // 单元
        map.put("unit",register.getUnit());
        // 门牌号
        map.put("house",register.getHouse());
        // 物业社区id
        map.put("userId",register.getUserId());
        // 物业社区名称
        map.put("workNo",register.getBlock().getUser().getWorkNo());

        return map;
    }

    @Override
    public String completeInfo(String registerId, String building, String unit, String house) {

        Register register = new Register();
        register.setId( Integer.parseInt( registerId ) );
        register.setBuilding( building );
        register.setUnit( unit );
        register.setHouse( house );

        try {
            registerMapper.update( register );
        } catch (DataAccessException e) {
            Log.error("完善注册用户信息失败，服务器异常");
            return "更新失败，服务器异常";
        }

        return "";
    }

    @Override
    public String registerGetCode(String registerId, String phone, String type) {

        Register register = registerMapper.find( Integer.parseInt( registerId ) );

        if ( !register.getPhone().equals( phone ) ) return "手机号与该账号绑定的手机号不匹配";

        String msg;
        if ( "4".equals( type ) ) {
            // 修改绑定手机号第二步获取验证码
            msg = commentService.getCode( phone, 1 );
        } else {
            // 2为重置密码  3为更改绑定手机号
            int t = "2".equals( type ) ? 2 : 3;
            msg = commentService.getCode( phone, t );
        }

        if ( !StringUtil.isBlank( msg ) ) return msg;

        return null;
    }

    @Resource private CommentService commentService;
    @Resource private RegisterMapper registerMapper;
    @Resource private BindVerifyMapper bindVerifyMapper;
    @Resource private TokenHistoryMapper historyMapper;
}
